# coding: utf-8

import app.tools as tool
from PyQt4 import QtCore, QtGui
from app.tools.dialog import MessageBox
from app.ui.tab.tab_page_abstract import TabPageAbstract


class TabPageString(TabPageAbstract):

    def __init__(self, tab, item, factory, name):
        super(TabPageString, self).__init__(tab, item, factory, name)
        self.parent = super(TabPageString, self)
        self.name = name
        self.factory = factory
        self.tab_widget_page = self.parent.get_instance()

        self.two_vertical_box_layout = QtGui.QVBoxLayout()
        self.two_horizontal_box_layout = QtGui.QHBoxLayout()

        self.string_value_label = QtGui.QLabel(self.tab_widget_page)
        self.string_value_label.setObjectName(tool._from_utf8("string_value_label"))
        self.string_value_label.setText(tool._from_utf8('Value:'))
        self.two_horizontal_box_layout.addWidget(self.string_value_label)

        two_spacer_item = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.two_horizontal_box_layout.addItem(two_spacer_item)

        self.value_format_label = QtGui.QLabel(self.tab_widget_page)
        self.value_format_label.setObjectName(tool._from_utf8("value_format_label"))
        self.value_format_label.setText(tool._from_utf8('View value as:'))
        self.two_horizontal_box_layout.addWidget(self.value_format_label)

        self.value_format_select = self.parent.get_combo_box(self.tab_widget_page)
        self.two_horizontal_box_layout.addWidget(self.value_format_select)
        self.two_vertical_box_layout.addLayout(self.two_horizontal_box_layout)

        self.value_text = QtGui.QTextEdit(self.tab_widget_page)
        self.value_text.setObjectName(tool._from_utf8("value_text"))
        self.value_text.setText(tool._from_utf8(self.factory.get(self.name)))
        self.two_vertical_box_layout.addWidget(self.value_text)
        self.two_vertical_box_layout.setStretch(0, 1)
        self.two_vertical_box_layout.setStretch(1, 9)

        self.parent.add_layout(self.two_vertical_box_layout)
        self.parent.set_stretch(0, 1)
        self.parent.set_stretch(1, 9)

    def event_save_clicked(self):
        ttl = self.factory.ttl(self.name)
        value = self.value_text.toPlainText()
        self.factory.set(self.name, value)
        if ttl > 0:
            self.factory.expire(self.name, ttl)
        MessageBox.info('tips', 'save success!')

    def event_format_changed(self, index):
        import json
        from lib.tools.type import TabComboBoxFormat
        value = self.factory.get(self.name)
        type = TabComboBoxFormat.parse(index)
        if type == TabComboBoxFormat.Text:
            new_value = value
        elif type == TabComboBoxFormat.Json:
            new_value = json.dumps(json.loads(value), indent=4)
        else:
            new_value = value
        self.value_text.setText(tool._from_utf8(new_value))
